Grokking Google Coding Interview
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Introduction
Who Should Take This Course?
Google Easy
Add Binary (easy)
Solution: Add Binary
Valid Mountain Array (easy)
Solution: Valid Mountain Array
Set Mismatch (easy)
Solution: Set Mismatch
Is Subsequence (easy)
Solution: Is Subsequence
Length of Last Word (easy)
Solution: Length of Last Word
Search Insert Position (easy)
Solution: Search Insert Position
Repeated Substring Pattern (easy)
Solution: Repeated Substring Pattern
Monotonic Array (easy)
Solution: Monotonic Array
Count Nodes Equal to Average of Subtree (easy)
Solution: Count Nodes Equal to Average of Subtree
Find the Difference (easy)
Solution: Find the Difference
How Many Numbers Are Smaller Than the Current Number (easy)
Solution: How Many Numbers Are Smaller Than the Current Number
Binary Tree Paths (easy)
Solution: Binary Tree Paths
Find the Difference of Two Arrays (easy)
Solution: Find the Difference of Two Arrays
Merge Strings Alternately (easy)
Solution: Merge Strings Alternately
Reverse a LinkedList (easy)
Solution: Reverse a LinkedList
Gray Code (medium)
Solution: Gray Code
2 Keys Keyboard (medium)
Solution: 2 Keys Keyboard
Arithmetic Slices (medium)
Solution: Arithmetic Slices
Unique Length-3 Palindromic Subsequences (medium)
Solution: Unique Length-3 Palindromic Subsequences
Minimum Difference Between Largest and Smallest Value in Three Moves (medium)
Solution: Minimum Difference Between Largest and Smallest Value in Three Moves
Letter Combinations of a Phone Number (medium)
Solution: Letter Combinations of a Phone Number
01 Matrix (medium)
Solution: 01 Matrix
Maximum Points You Can Obtain from Cards (medium)
Solution: Maximum Points You Can Obtain from Cards
Strobogrammatic Number II (medium)
Solution: Strobogrammatic Number II
Maximum Length of Semi-Decreasing Subarrays (medium)
Solution: Maximum Length of Semi-Decreasing Subarrays
Minimum Area Rectangle (medium)
Solution: Minimum Area Rectangle
Count Unreachable Pairs of Nodes in an Undirected Graph (medium)
Solution: Count Unreachable Pairs of Nodes in an Undirected Graph
Single Number II (medium)
Solution: Single Number II
4Sum II (medium)
Solution: 4Sum II
Furthest Building You Can Reach (medium)
Solution: Furthest Building You Can Reach
Minimizing Array After Replacing Pairs With Their Product (medium)
Solution: Minimizing Array After Replacing Pairs With Their Product
Fair Distribution of Cookies (medium)
Solution: Fair Distribution of Cookies
Find Leaves of Binary Tree (medium)
Solution: Find Leaves of Binary Tree
Rotate Image (medium)
Solution: Rotate Image
Combination Sum (medium)
Solution: Combination Sum
Implement Trie (Prefix Tree) (medium)
Solution: Implement Trie (Prefix Tree)
Number of Islands (medium)
Solution: Number of Islands
Edit Distance (medium)
Solution: Edit Distance
Container With Most Water (Medium)
Solution: Container With Most Water
Meeting Rooms II (medium)
Solution: Meeting Rooms II
Shortest Subarray with Sum at Least K (hard)
Solution: Shortest Subarray with Sum at Least K
Reverse Pairs (hard)
Solution: Reverse Pairs
Nth Magical Number (hard)
Solution: Nth Magical Number
Candy (hard)
Solution: Candy
Arithmetic Slices II - Subsequence (hard)
Solution: Arithmetic Slices II - Subsequence
Burst Balloons (hard)
Solution: Burst Balloons
Sum of Distances in Tree (hard)
Solution: Sum of Distances in Tree
Maximum Score of a Good Subarray (hard)
Solution: Maximum Score of a Good Subarray
Trapping Rain Water (hard)
Solution: Trapping Rain Water
First Missing Positive (hard)
Solution: First Missing Positive
Solution: Add Binary

Problem Statement

Given two binary strings a and b, return a sum of a and b represented as binary strings.

Examples

  1. Example 1:

    • Input: a = "10110", b = "10101"
    • Expected Output: "101011"
    • Justification: The binary sum of "10110" (22 in decimal) and "10101" (21 in decimal) is "101011" (43 in decimal).
  2. Example 2:

    • Input: a = "111", b = "1"
    • Expected Output: "1000"
    • Justification: The binary sum of "111" (7 in decimal) and "1" (1 in decimal) is "1000" (8 in decimal).
  3. Example 3:

    • Input: a = "0", b = "0"
    • Expected Output: "0"
    • Justification: The binary sum of "0" and "0" remains "0".

Solution

To solve this problem, we'll iterate over the input strings from right to left, simulating the binary addition process. We choose this approach because it directly simulates how binary addition works, carrying over bits when necessary. Our solution needs to handle different lengths of binary strings and the carry that can occur after adding the last bits.

By processing the strings from the end towards the beginning, we can easily manage carries and ensure that we consider all bits in both strings. If one string is shorter, we'll treat missing bits as '0'. This method is effective because it mirrors manual binary addition, ensuring no bit is missed and carries are correctly applied, resulting in an accurate binary sum.

Step-by-Step Algorithm

  1. Initialize Variables:

    • Create a variable result to store the final binary sum as a string.
    • Initialize two index variables, i and j, to point to the last characters of strings a and b respectively.
    • Initialize a carry variable to 0, which will hold the carry-over value when adding two binary digits.
  2. Iterate Over Strings:

    • Use a loop to iterate while either i or j is non-negative, or carry is 1. This ensures that you continue addition until both strings are completely traversed and any remaining carry is processed.
  3. Calculate Sum:

    • Within the loop, for each position starting from the end, add the corresponding binary digits of a and b, along with the carry.
    • If i or j has gone negative (indicating one string is shorter), treat the missing digits as 0.
  4. Update Result and Carry:

    • Calculate the binary digit to be appended to the result (sum % 2) and update the carry (sum / 2).
    • Prepend the calculated digit to the result string.
  5. Handle Remaining Carry:

    • After the loop, if there's a remaining carry, prepend it to the result.
  6. Return the Result:

    • Return the result string, which now contains the binary sum of a and b.

Algorithm Walkthrough

Let's consider the input: a = "10110", b = "10101"

  1. Initialization:

    • result = ""
    • i = 4 (pointing to the last character of "10110")
    • j = 4 (pointing to the last character of "10101")
    • carry = 0
  2. First Iteration (rightmost digits):

    • a[i] = 0, b[j] = 1
    • sum = 0 + 1 + 0 (carry) = 1
    • result = sum%2 + result = 1%2 + "" = "1", carry = sum/2 = 1/2 = 0
    • i = 3, j = 3
  3. Second Iteration:

    • a[i] = 1, b[j] = 0
    • sum = 1 + 0 + 0 = 1
    • result = sum%2 + result = 1%2 + "1" ="11", carry = sum/2 = 1/2 = 0
    • i = 2, j = 2
  4. Third Iteration:

    • a[i] = 1, b[j] = 1
    • sum = 1 + 1 + 0 = 2
    • result = sum%2 + result = 2%2 + "11" = "011", carry = sum/2 = 2/2 = 1
    • i = 1, j = 1
  5. Fourth Iteration:

    • a[i] = 0, b[j] = 0
    • sum = 0 + 0 + 1 (carry) = 1
    • result = sum%2 + result = 1%2 + "011" = "1011", carry = sum/2 = 1/2 = 0
    • i = 0, j = 0
  6. Fifth Iteration:

    • a[i] = 1, b[j] = 1
    • sum = 1 + 1 + 0 = 2
    • result = sum%2 + result = 2%2 + "1011" = "01011", carry = sum/2 = 2/2 = 1
    • i = -1, j = -1
  7. Handle Remaining Carry:

    • Since carry = 1, result = "101011"
  8. Final Result:

    • The final binary sum is "101011", which is the correct sum of "10110" and "10101".
Image

Code

Java
Saved to Cloud

. . . .

Complexity Analysis

Time Complexity

, where N and M are the lengths of the two input binary strings, respectively. This is because we iterate through each string once, from end to start, in the worst case. The time complexity is determined by the longer string since we perform the addition digit by digit, including handling of the carry.

Space Complexity

, which is required for storing the result. In the worst case, the length of the result string will be max(N, M) + 1 (due to a possible carry that adds an extra digit).

Add Binary (easy)
Valid Mountain Array (easy)
Mark as Completed

On this page

Problem Statement

Examples

Solution

Step-by-Step Algorithm

Algorithm Walkthrough

Code

Complexity Analysis

Time Complexity

Space Complexity